package com.cangmaomao.m_mePen.fragment

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import com.cangmaomao.lib.action.f_editSort
import com.cangmaomao.lib.action.f_sortList
import com.cangmaomao.lib.base.BaseFragment
import com.cangmaomao.lib.event.AppEvent
import com.cangmaomao.lib.event.SelectClassEvent
import com.cangmaomao.lib.utils.FileUtils.readFiles
import com.cangmaomao.lib.utils.initRecycler
import com.cangmaomao.lib.utils.toast
import com.cangmaomao.m_mePen.R
import com.cangmaomao.m_mePen.adapter.FileListAdapter
import com.cangmaomao.m_mePen.bean.FileListBean
import com.cangmaomao.m_mePen.contract.FileListContract
import com.cangmaomao.m_mePen.event.FileList
import com.cangmaomao.m_mePen.presenter.FileListPresenter
import kotlinx.android.synthetic.main.f_file_list.*
import kotlinx.android.synthetic.main.item_file_list.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.util.*

class FileListFragment : BaseFragment<FileListContract.Presenter>(), FileListContract.View {

    private lateinit var adapter: FileListAdapter

    override val contentViewLayoutID: Int
        get() = R.layout.f_file_list

    override fun readLocalFile(): Array<File> = readFiles()!!

    override fun initView(savedInstanceState: Bundle?) {
        initToolBarNav(getString(R.string.file_list), getString(R.string.edit_sort))
        initRecycler(recyclerView)
        adapter = FileListAdapter()
        recyclerView.adapter = adapter

        FileListPresenter(this)
        p.start()


    }

    override fun showLocalFile(list: MutableList<FileListBean>) {
        adapter.addList(list)
        adapter.setOnItemClickListener { _, data, pos ->
            data as FileListBean
            if (data.fileNum == 0) {
                toast("当前文件夹中无任何文件!")
                return@setOnItemClickListener
            }
            val bundle = Bundle()
            bundle.putString("pos", pos.toString())
            bundle.putString("name", data.fileName)
            EventBus.getDefault().post(AppEvent(f_sortList, bundle))
        }
    }

    override fun onRightClick() {
        val list = adapter.data
        list.forEach {
            it.isEdit = true
        }
        adapter.notifyDataSetChanged()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun messageEvent(event: FileList) {
        adapter.data[event.pos].fileNum = event.size
        adapter.notifyItemChanged(event.pos)
    }

}
